package com.jajahome.feature.user.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jajahome.R;
import com.jajahome.base.BaseActivity;
import com.jajahome.constant.Constant;
import com.jajahome.feature.user.adapter.CrowImgAdapter;
import com.jajahome.feature.user.adapter.CrowViewPagerAdapter;
import com.jajahome.model.CrowDetailModel;
import com.jajahome.network.ApiImp;
import com.jajahome.network.BaseReq;
import com.jajahome.util.StringUtil;
import com.jajahome.util.TimeUtil;
import com.jajahome.widget.HorizontalRecycleView;
import com.jajahome.widget.ItemWebView;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by tuxuesong on 2018/5/14.
 */

public class CrowDetailAct extends BaseActivity implements CrowImgAdapter.
        OnImgItemClickListener {

    @BindView(R.id.ibtn_back)
    ImageButton imageButton;
    @BindView(R.id.textView2)
    TextView title;
    @BindView(R.id.crow_super_value)
    TextView superValue;
    @BindView(R.id.crow_title)
    TextView crowTitle;
    @BindView(R.id.crow_origin)
    TextView crowOrigin;
    @BindView(R.id.crow_discount)
    TextView crowDiscount;
    @BindView(R.id.crow_introduce)
    TextView crowIntroduce;
    @BindView(R.id.crow_alread_gold)
    TextView alreadyGold;
    @BindView(R.id.progress)
    ProgressBar bar;
    @BindView(R.id.tarAmount)
    TextView tarAmount;
    @BindView(R.id.buy_count)
    TextView buyCount;
    @BindView(R.id.send_time)
    TextView sendTime;
    @BindView(R.id.discount)
    TextView disCount;
    @BindView(R.id.top_view_pager)
    ViewPager mViewPager;
    @BindView(R.id.top_img_recycle)
    HorizontalRecycleView mHorizontalRecyclerView;
    @BindView(R.id.origin)
    TextView originPrice;
    @BindView(R.id.progressDesc)
    TextView progressDesc;
    @BindView(R.id.service)
    TextView serTextView;
    @BindView(R.id.crow_detail)
    TextView detailCrow;
    @BindView(R.id.type_time)
    TextView typeTime;
    @BindView(R.id.crow_detail_web)
    ItemWebView webView;
    private CrowDetailModel detailModel;
    private CrowViewPagerAdapter mAdpater;
    private CrowImgAdapter imgAdapter;
    private MyThread timeThread;

    private WebSettings webSettings;
    public static final String CROW_ID = "crow_id";
    public static final String AMRAISED = "amRaised";
    public static final String TARAMOUNT = "tarAmount";
    public static final String MEMO = "memo";
    public static final String TYPE = "type";
    public static String ENDTIME = "endtime";

    private String postage;
    private String ID;
    private String mEmo;
    private String type;
    private String aMraised;
    private String tAramount;
    private String endTime;
    private String buy_Count;

    @Override
    protected int getViewId() {
        return R.layout.act_crow_detail;
    }

    @Override
    protected void initEvent() {
        postage = getIntent().getStringExtra(ChipsAct.POSTAGE);
        type = getIntent().getStringExtra(TYPE);
        mEmo = getIntent().getStringExtra(MEMO);
        ID = getIntent().getStringExtra(CROW_ID);
        endTime = getIntent().getStringExtra(ENDTIME);
        aMraised = getIntent().getStringExtra(AMRAISED);
        tAramount = getIntent().getStringExtra(TARAMOUNT);
        buy_Count = getIntent().getStringExtra(ChipsAct.BUYCOUNT);

        if (!StringUtil.isEmpty(aMraised) && !StringUtil.isEmpty(tAramount)) {
            bar.setMax(Integer.parseInt(StringUtil.spilStr(tAramount)));
            bar.setProgress(Integer.parseInt(StringUtil.spilStr(aMraised)));
        }

        mAdpater = new CrowViewPagerAdapter(mContext, null);
        mViewPager.setAdapter(mAdpater);
        imgAdapter = new CrowImgAdapter();
        mHorizontalRecyclerView.setAdapter(imgAdapter);
        typeTime.setText("");
        getList();
        setListener();
        //加载详情
        getDetailWeb();
        timeThread = new MyThread();
        new Thread(timeThread).start();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getList();
    }

    private void getList() {
        BaseReq req = new BaseReq();
        req.setCmd(Constant.crowd_funding_detail);
        BaseReq.ContentBean contentBean = new BaseReq.ContentBean();
        if (StringUtil.isEmpty(ID)) {
            Toast.makeText(this, "众筹id不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        contentBean.setId(Integer.parseInt(ID));
        req.setContent(contentBean);
        final Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(req));
        ApiImp.get().crowd_funding_detail(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CrowDetailModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(CrowDetailModel model) {
                        Log.e("model", new Gson().toJson(model));
                        detailModel = model;
                        setData();
                    }
                });
    }


    private void setListener() {
        superValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (detailModel == null) {
                    return;
                }
                final List<CrowDetailModel.DataEntity.CrowdFundingEntity> crowd_funding = detailModel.getData().getCrowd_funding();
                Intent intent = new Intent(mContext, ChipsAct.class);
                intent.putExtra(ChipsAct.CROWID, Integer.parseInt(ID));
                intent.putExtra(ChipsAct.POSTAGE, Integer.parseInt(postage));
                intent.putExtra(ChipsAct.STATE, type);
                intent.putExtra(ChipsAct.MEMO, mEmo);
                intent.putExtra(ChipsAct.MODEL, (Serializable) crowd_funding);
                startActivity(intent);
            }
        });

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        imgAdapter.setListener(this);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                imgAdapter.setmIndex(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        title.setText("众筹详情");

    }


    private void setData() {
        List<CrowDetailModel.DataEntity.CrowdFundingEntity> crowd_funding = detailModel.getData().getCrowd_funding();
        CrowDetailModel.DataEntity.CrowdFundingEntity crowdEntity = new CrowDetailModel.DataEntity.CrowdFundingEntity();
        //排序
        Collections.sort(crowd_funding);
//        for (CrowDetailModel.DataEntity.CrowdFundingEntity crowdEntity1 : crowd_funding){
//            Log.e("crowdEntity1",new Gson().toJson(crowdEntity1));
//        }
        crowdEntity = crowd_funding.get(0);
        String crowdName = crowdEntity.getName();
        if (!StringUtil.isEmpty(crowdName)) {
            crowTitle.setText(crowdName);
        }

        String crowPrice = crowdEntity.getPrice();
        if (!StringUtil.isEmpty(crowPrice)) {
            crowDiscount.setText(Constant.YUAN + StringUtil.spilStr(crowPrice));
            disCount.setText(Constant.YUAN + StringUtil.spilStr(crowPrice));
        }
        String oPrice = crowdEntity.getOriginal() + "";
        if (!StringUtil.isEmpty(oPrice)) {
            originPrice.setText("原价" + Constant.YUAN + StringUtil.spilStr(oPrice));
            crowOrigin.setText("原价" + Constant.YUAN + StringUtil.spilStr(oPrice));
        }
        String itemTroduce = crowdEntity.getItemiTroduce();
        if (!StringUtil.isEmpty(itemTroduce)) {
            crowIntroduce.setText(itemTroduce);
        }
//        String buyCountdesc = crowdEntity.getBuy_count();
//        if (!StringUtil.isEmpty(buyCountdesc)) {
//            buyCount.setText(buyCountdesc);
//        }
        //支持人数
        buyCount.setText(buy_Count);
        //包邮不包邮  mEmo为空不显示
        if(StringUtil.isEmpty(mEmo)){
            serTextView.setVisibility(View.GONE);
        }else {
            serTextView.setText("服务："+mEmo);
            serTextView.setVisibility(View.VISIBLE);
        }

//        if (postage.equals("0")) {
//            serTextView.setVisibility(View.GONE);
//        } else if (postage.equals("1")) {
//
//        }

        String tips = crowdEntity.getTips();
        if (!StringUtil.isEmpty(tips)) {
//            detailCrow.setText(tips);
        }

        String state = crowdEntity.getState();
        if (state.equals("0")) {
            typeTime.setText("即将开始");
        } else if (state.equals("1")) {
            typeTime.setText("剩余时间");
        }
        alreadyGold.setText(Constant.YUAN + StringUtil.spilStr(aMraised));
        tarAmount.setText(Constant.YUAN + StringUtil.spilStr(tAramount));
        if ((Float.parseFloat(aMraised) / Float.parseFloat(tAramount))*100>=999){
            progressDesc.setText("＞999%");
        }else {
            progressDesc.setText(StringUtil.spilStr(((Float.parseFloat(aMraised) / Float.parseFloat(tAramount)) * 100) + "") + "%");
        }
        if (crowd_funding == null || crowd_funding.size() == 0) {
            return;
        }
        mAdpater.setItemPreviewImgs(crowd_funding);
        imgAdapter.resetItems(crowd_funding);
    }


    @Override
    public void onItemClick(int index) {
        mViewPager.setCurrentItem(index);
    }

    class MyThread implements Runnable {
        //用来停止线程
        boolean endThread;

        @Override
        public void run() {
            while (!endThread) {
                try {
                    Thread.sleep(1000);
                    Message message = new Message();
                    message.what = 2;
                    //发送信息给handler
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    List<CrowDetailModel.DataEntity.CrowdFundingEntity> crowd_funding = detailModel.getData().getCrowd_funding();
                    Long countdown = crowd_funding.get(0).getCountdown();
                    String state = crowd_funding.get(0).getState();
                    if (state.equals("3") && !StringUtil.isEmpty(state)) {
                        sendTime.setText("");
                        typeTime.setText("");
                        break;
                    }

                    if (state.equals("2")||state.equals("4")||state.equals("5") && !StringUtil.isEmpty(state)) {
                        sendTime.setText("");
                        typeTime.setText("");
                        break;
                    }
                    String sTime = TimeUtil.getHMS(countdown);
                    if (countdown == 0) {
                        sendTime.setText(sTime);
                        getList();
                        break;
                    }
                    crowd_funding.get(0).setCountdown(countdown - 1);
                    String sTime1 = TimeUtil.getHMS(countdown);
                    if (!StringUtil.isEmpty(sTime1)) {
                        sendTime.setText(sTime1);
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void getDetailWeb(){
        webView.setFocusable(false);
        webSettings = webView.getSettings();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setBlockNetworkImage(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.setWebViewClient(new GoodsDetailWebViewClient());
        String picTextUrl = Constant.ITEM_DETAIL_SEC + ID;
        webView.loadUrl(picTextUrl);
    }
    private class GoodsDetailWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            webSettings.setBlockNetworkImage(false);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }
    }

}
